import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom'
import { Swiper } from 'react-vant'
import { Header } from '../../components/header'
import { CartO, ChatO, ShopO } from '@react-vant/icons'
import { ActionBar } from 'react-vant'
import { useDispatch } from 'react-redux';

const Index = () => {
  // 获取动态路由参数 id
  const { id } = useParams();
  const [data, setData] = useState({})
  const dispatch = useDispatch()
  const getDetail = (id) => {
    axios.get('/api/detail', { params: { id } }).then(resp => {
      // console.log(resp.data)
      setData(resp.data.data)
    })
  }
  const handleAddToCar = () => {
    // 加入购物车
    dispatch({
      type: 'addCar', payload: {
        ...data,
        count: 1,
        state: true
      }
    })
  }

  useEffect(() => {
    getDetail(id)
  }, [])

  if (!data.image) {
    return <div>数据加载中...</div>
  }

  return (
    <div>
      {/* 头部 */}
      <Header></Header>
      {/* 轮播图 */}
      <Swiper>
        {
          data.image.map((v, i) => {
            return <Swiper.Item key={i}>
              <img src={v} width="100%" height={200} alt="" />
            </Swiper.Item>
          })
        }
      </Swiper>
      {/* 内容 */}
      <div>
        <h3>{data.title}</h3>
        <p>{data.address}</p>
        <p>{data.desc}</p>
        <p>单价：{data.price}</p>
        <p>销售：{data.sell}</p>
      </div>
      {/* 底部 */}
      <ActionBar>
        <ActionBar.Icon
          icon={<ChatO />}
          text='客服'
          onClick={() => console.log('chat click')}
        />
        <ActionBar.Icon
          icon={<CartO />}
          text='购物车'
          onClick={() => console.log('cart click')}
        />
        <ActionBar.Icon
          icon={<ShopO />}
          text='店铺'
          onClick={() => console.log('shop click')}
        />
        <ActionBar.Button
          type='danger'
          text='加入购物车'
          onClick={() => handleAddToCar()}
        />
      </ActionBar>
    </div>
  )
}


export default Index